'use client'

import React, { useState } from 'react'
import Calendar from 'react-calendar'
import 'react-calendar/dist/Calendar.css'

type ValuePiece = Date | null
type Value = ValuePiece | [ValuePiece, ValuePiece]

// 班次类型
type ShiftType = 'night' | 'day' | 'rest'

// 班次信息接口
interface ShiftInfo {
  type: ShiftType
  startTime: string
  endTime: string
  label: string
  color: string
}

const WorkCalendar: React.FC = () => {
  const [value, setValue] = useState<Value>(new Date())
  const [currentDate, setCurrentDate] = useState(new Date())

  // 基准日期：2025年9月1日晚班开始
  const baseDate = new Date(2025, 8, 1) // 月份从0开始，所以8代表9月
  
  // 计算指定日期的班次信息
  const getShiftInfo = (date: Date): ShiftInfo => {
    // 计算从基准日期开始的天数
    const daysDiff = Math.floor((date.getTime() - baseDate.getTime()) / (1000 * 60 * 60 * 24))
    
    // 3天一个循环：晚班(第0天) -> 休息(第1天) -> 白班(第2天)
    const cyclePosition = ((daysDiff % 3) + 3) % 3 // 确保结果为正数
    
    switch (cyclePosition) {
      case 0: // 晚班
        return {
          type: 'night',
          startTime: '19:00',
          endTime: '次日07:00',
          label: '晚班',
          color: '#4c51bf'
        }
      case 1: // 休息
        return {
          type: 'rest',
          startTime: '07:00',
          endTime: '次日07:00',
          label: '休息',
          color: '#38a169'
        }
      case 2: // 白班
        return {
          type: 'day',
          startTime: '07:00',
          endTime: '19:00',
          label: '白班',
          color: '#d69e2e'
        }
      default:
        return {
          type: 'rest',
          startTime: '',
          endTime: '',
          label: '休息',
          color: '#38a169'
        }
    }
  }

  // 生成年份选项 (当前年份前后10年)
  const currentYear = new Date().getFullYear()
  const years = Array.from({ length: 21 }, (_, i) => currentYear - 10 + i)

  // 月份选项
  const months = [
    { value: 0, label: '1月' },
    { value: 1, label: '2月' },
    { value: 2, label: '3月' },
    { value: 3, label: '4月' },
    { value: 4, label: '5月' },
    { value: 5, label: '6月' },
    { value: 6, label: '7月' },
    { value: 7, label: '8月' },
    { value: 8, label: '9月' },
    { value: 9, label: '10月' },
    { value: 10, label: '11月' },
    { value: 11, label: '12月' },
  ]

  // 处理年份变化
  const handleYearChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
    const selectedYear = parseInt(event.target.value)
    const newDate = new Date(currentDate)
    newDate.setFullYear(selectedYear)
    setCurrentDate(newDate)
  }

  // 处理月份变化
  const handleMonthChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
    const selectedMonth = parseInt(event.target.value)
    const newDate = new Date(currentDate)
    newDate.setMonth(selectedMonth)
    setCurrentDate(newDate)
  }

  // 格式化当前显示的年月
  const formatCurrentDate = (date: Date) => {
    return `${date.getFullYear()}年${date.getMonth() + 1}月`
  }

  return (
    <div className="calendar-container">
      <div className="calendar-header">
        <h1 className="calendar-title">工作日历</h1>
        <div className="date-selectors">
          <div className="date-selector">
            <label htmlFor="year-select">年份</label>
            <select
              id="year-select"
              value={currentDate.getFullYear()}
              onChange={handleYearChange}
            >
              {years.map((year) => (
                <option key={year} value={year}>
                  {year}年
                </option>
              ))}
            </select>
          </div>
          <div className="date-selector">
            <label htmlFor="month-select">月份</label>
            <select
              id="month-select"
              value={currentDate.getMonth()}
              onChange={handleMonthChange}
            >
              {months.map((month) => (
                <option key={month.value} value={month.value}>
                  {month.label}
                </option>
              ))}
            </select>
          </div>
        </div>
      </div>

      <div className="current-date">
        <h2>当前显示: {formatCurrentDate(currentDate)}</h2>
      </div>

      <Calendar
        onChange={setValue}
        value={value}
        activeStartDate={currentDate}
        onActiveStartDateChange={({ activeStartDate }) => {
          if (activeStartDate) {
            setCurrentDate(activeStartDate)
          }
        }}
        locale="zh-CN"
        showNavigation={true}
        showNeighboringMonth={true}
        formatShortWeekday={(_locale, date) => {
          const weekdays = ['日', '一', '二', '三', '四', '五', '六']
          return weekdays[date.getDay()]
        }}
        tileContent={({ date, view }) => {
          if (view === 'month') {
            const shiftInfo = getShiftInfo(date)
            const today = new Date()
            const isToday = date.getDate() === today.getDate() &&
              date.getMonth() === today.getMonth() &&
              date.getFullYear() === today.getFullYear()

            return (
              <div className="shift-info">
                <div 
                  className={`shift-badge ${shiftInfo.type}`}
                  style={{ backgroundColor: shiftInfo.color }}
                >
                  {shiftInfo.label}
                </div>
                {isToday && <div className="today-marker">今天</div>}
              </div>
            )
          }
          return null
        }}
      />

      <div style={{ marginTop: '1rem', color: '#666', fontSize: '14px' }}>
        {value instanceof Date && (
          <div>
            <p>选中日期: {value.toLocaleDateString('zh-CN', {
              year: 'numeric',
              month: 'long',
              day: 'numeric',
              weekday: 'long'
            })}</p>
            {(() => {
              const selectedShift = getShiftInfo(value)
              return (
                <div className="selected-shift-info">
                  <p>班次安排: 
                    <span 
                      className={`shift-badge ${selectedShift.type}`}
                      style={{ 
                        backgroundColor: selectedShift.color,
                        marginLeft: '8px',
                        padding: '2px 8px',
                        borderRadius: '4px',
                        color: 'white',
                        fontSize: '12px'
                      }}
                    >
                      {selectedShift.label}
                    </span>
                  </p>
                  <p>工作时间: {selectedShift.startTime} - {selectedShift.endTime}</p>
                </div>
              )
            })()}
          </div>
        )}
      </div>

      <div className="shift-legend">
        <h3>排班说明</h3>
        <div className="legend-items">
          <div className="legend-item">
            <span className="shift-badge night">晚班</span>
            <span>19:00 - 次日07:00 (12小时)</span>
          </div>
          <div className="legend-item">
            <span className="shift-badge rest">休息</span>
            <span>07:00 - 次日07:00 (24小时)</span>
          </div>
          <div className="legend-item">
            <span className="shift-badge day">白班</span>
            <span>07:00 - 19:00 (12小时)</span>
          </div>
        </div>
        <p className="shift-cycle">循环周期：晚班 → 休息 → 白班 → 晚班...</p>
      </div>
    </div>
  )
}

export default WorkCalendar
